package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"goods_svc/goods"
	"goods_svc/internal/svc"
	"goods_svc/models/cache"
	"goods_svc/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品列表
func (l *ShopListLogic) ShopList(in *goods.ShopListRequest) (*goods.ShopListResponse, error) {
	// todo: add your logic here and delete this line

	//分页
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	//去mysql数据库查询一下
	var shops []mysql.Shop
	mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Order("created_at desc").Find(&shops)
	//使用缓存
	key := fmt.Sprintf("shop_list_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &shops)
	} else {
		marshal, _ := json.Marshal(shops)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	}
	//实现展示
	var shopList []*goods.ShopList
	for _, shop := range shops {
		list := goods.ShopList{
			UserId: int64(shop.UserId),
			Name:   shop.Name,
			Price:  float32(shop.Price),
			Stock:  int64(shop.Stock),
		}
		shopList = append(shopList, &list)
	}
	return &goods.ShopListResponse{
		List: shopList,
	}, nil
}
